
import 'dart:convert';
import 'dart:typed_data';

import 'package:app/common/tool.dart';
import 'package:app/components/base_scaffold_appbar.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:bot_toast/bot_toast.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';

import 'package:get/get_core/src/get_main.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:get/get.dart';

import '../../common/colors.dart';
import '../../components/bottom_page.dart';
import '../../services/address.dart';
import '../../services/dio_manager.dart';
import '../../utils/persisten_storage.dart';
import 'news_comment_detail_page.dart';
import 'news_detail_comment_model.dart';
import 'news_detail_model.dart';

class NewDetailPage extends StatefulWidget{

  String newsId;


  NewDetailPage(this.newsId, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState

    return NewDetailPageState();
  }
}

class NewDetailPageState extends State<NewDetailPage>{


  // GlobalKey<_TextWidgetState> textKey = GlobalKey();

  List commentList = [];

  final TextEditingController _tfEditingController = TextEditingController();

  final FocusNode _commentFocus = FocusNode();


  late StateSetter _stateSetter;


  NewsDetailModel? _model;

  String hintTextStr = '写评论';

  var replyId;

  void requestData()async{

    var json = await DioManager().kkRequest('${Address.newsDetail}/${widget.newsId}',
      method: 'get',);

    if(json['errmsg']=='no'){
      // LKToast.toast(context,msg: json['message']);
      BotToast.showText(text: json['message']);
      Get.back();
    }

    NewsDetailModel model = NewsDetailModel.fromJson(json);

    _model = model;
    //
    // if(dataList[0]['my_follows']=='0'){
    //   _isCollection = false;
    //
    // }else{
    //   _isCollection = true;
    // }

    setState(() {

    });

  }

  var commentPage = 1;

/// 请求评论
  void requestComment(var isHeader)async{

    var params = {
      'page':commentPage,
      'limit':'100',
      'id':'${widget.newsId}',
      'comment_id':'0',  //上级评论
    };
    var json = await DioManager().
    kkRequest('${Address.host}/cms.news.comment/page/read',params: params,method: 'get');

    NewsDetailCommentModel model = NewsDetailCommentModel.fromJson(json);

    if(model.data != null){
      commentList = model.data!;
    }

    setState(() {

    });
  }

/// 发送评论
  void sendComment(String msg,String parentID)async{

    Get.dialog(Center(
      child: CircularProgressIndicator(),
    ));
    var params = {
      'news_id':'${widget.newsId}',
      'parent_id':'${parentID}',
      'comment':msg,
    };
    var json = await DioManager().kkRequest('${Address.homeHost}${Address.newsComment}',
        bodyParams: params);

    if(json['errmsg'] == 'ok'){

      BotToast.showText(text: '${json['message']}');

      _tfEditingController.text = '';

      requestComment(true);

      Get.back();

      // textKey.currentState!.setState(() {
      //
      // });

    }else{

    }
  }

  /// 收藏请求
  /// 1-收藏 0-取消
  void requestCollection(int status)async{


    var params = {
      'news_id':'${widget.newsId}',
      'status':status,
    };
    var json = await DioManager().kkRequest('${Address.newsCollect}',
        header: {'access_token': await PersistentStorage().getStorage('acctoken'),
          'user_id':await PersistentStorage().getStorage('uid'),
          'company_id':await PersistentStorage().getStorage('companyId')
        },
        bodyParams: params);

    if(json['errmsg'] == 'ok'){
      BotToast.showText(text: '收藏成功');
      requestData();
      // LKToast.toast(context,msg: json['message'],position: ToastPostion.bottom);
    }else{

    }


    // setState(() {
    //   if(a ==3){
    //     _isCollection = false;
    //   }else{
    //     _isCollection = true;
    //   }
    // });



    _stateSetter((){

      // _isCollection = true;
    });

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _commentFocus.addListener(() {
      print('是否是焦点::${_commentFocus.hasFocus}');
      if(!_commentFocus.hasFocus){
        hintTextStr = '请评论';
        replyId = 0;
      }
    });
    requestData();
    requestComment(true);
  }

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return(
        Scaffold(
          appBar:BaseAppBar(
            preferredSize: Size(Get.width,AppTool.appBarHEIGHT),
            child: Text(''),
            action: [
              IconButton(onPressed: (){
                Share.share('DTCloud-App \n ${Address.homeHost}${_model!.data!.share_url}');
              }, icon: Image.asset('images/news_shard.png',width: 24,height: 24,color: Colors.white,))
            ],
          ),

          // AppBar(
          //   actions: [
          //     IconButton(onPressed: (){
          //       Share.share('DTCloud-App \n ${Address.homeHost}${_model!.data!.share_url}');
          //     }, icon: Image.asset('images/news_shard.png',width: 25,height: 25,))
          //   ],
          //   title: Text(''),
          // ),

          body: SafeArea(
            bottom: false,
            child: Stack(
              children: [
                ListView(
                  keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            _model!.data!.title!,
                            style: TextStyle(fontWeight: FontWeight.w600,fontSize: 22),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(left: 10),
                          child: Text('${_model!.data!.createDate}',style: TextStyle(color:Colors.grey,fontSize: 12),),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 10,right: 10,top: 10),
                      child:  HtmlWidget(
                        _model!.data!.content,
                      ),
                    ),

                    Container(
                      margin: EdgeInsets.only(top: 25),
                      color: AppColor.lineColor,
                      width: Get.width,
                      height: 5,
                    ),
                    /// 评论
                    Container(
                      padding:const EdgeInsets.only(bottom: 10,left: 10,top: 10),
                      child: const Text('全部评论',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 16),),
                    ),


                    _model?.data?.newsproperty_commtf==false?Container(
                      color: Colors.white,
                      height: 100,
                      alignment: Alignment.topCenter,
                      child: Text('此内容无法评论',style: TextStyle(fontSize: 13,color: AppColor.smallTextColor),),
                    ): Column(
                        children: commentWidget()
                    ),


                    _model?.data?.newsproperty_commtf==false?Container(

                    ):Container(
                      margin: EdgeInsets.only(bottom: 40),
                      height: 50,
                      // color: Colors.red,
                      child:  Center(
                        child: Text('已显示全部评论',
                          style: TextStyle(fontSize: 12,color: AppColor.smallTextColor),),
                      ),
                    )

                  ],
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    padding: EdgeInsets.only(top: 5),
                      alignment: Alignment.topCenter,
                      color: Colors.grey[200],
                      width: double.infinity,
                      height: 45+MediaQuery.of(context).padding.bottom,
                      child: Row(
                        children: [
                          IconButton(icon:Icon(Icons.arrow_back,color: Colors.black54,), onPressed: (){
                            Get.back();
                          }),
                          Container(
                            padding: EdgeInsets.only(left:5),
                            width: Get.width-150,
                            height: 35,
                            // margin: EdgeInsets.only(left: 50,right: 150,bottom: 5,top: 5),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(
                                Radius.circular(17.0),
                              ),
                            ),
                            child:Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Center(
                                child: TextField(
                                  enabled:_model?.data?.newsproperty_commtf==false?false:true,
                                  onSubmitted: (str){
                                    print('send');
                                    sendComment(str,'${replyId}');
                                  },
                                  onChanged: (str){
                                    print('onChanged');
                                  },
                                  textInputAction: TextInputAction.none,
                                  focusNode: _commentFocus,
                                  maxLines: 1,
                                  controller: _tfEditingController,
                                  style: const TextStyle(fontSize: 13),
                                  decoration:  InputDecoration(
                                    // contentPadding: EdgeInsets.only(left: 25),
                                    isCollapsed: true,
                                    hintText: _model?.data?.newsproperty_commtf==false?'此内容不支持评论':hintTextStr,
                                    hintStyle: TextStyle(fontSize: 14),
                                    //去掉搜索框默认的线
                                    border: InputBorder.none,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          StatefulBuilder(
                              builder: (BuildContext context, StateSetter stateSetter) {
                                _stateSetter = stateSetter;
                                return IconButton(
                                  icon:_model!.data!.is_collect==false?
                                  Image.asset('images/collection_icon1.png',width: 25,height: 25,
                                  ):Image.asset('images/collection_selection.png',width: 22,height: 22,
                                    color: Colors.orange,
                                  ),
                                  onPressed: (){
                                    if(_model!.data!.is_collect==true){
                                      requestCollection(0);
                                    }else{
                                      requestCollection(1);
                                    }

                                  },
                                );
                              }
                          ),

                          IconButton(
                            icon: Image.asset('images/send.png',width: 20,height: 20,),
                            onPressed: (){

                              if(_model?.data?.newsproperty_commtf==false){
                                hintTextStr = '此内容支持评论';
                                return;
                              }
                              if(_tfEditingController.text.isEmpty){
                                // LKToast.toast(context,msg: '请输入评论内容');
                                BotToast.showText(text: '请输入评论内容');
                                return;
                              }
                              if(hintTextStr == '写评论'){
                                sendComment(_tfEditingController.text,'0');
                              }else{
                                sendComment(_tfEditingController.text,'${replyId}');
                              }
                              _commentFocus.unfocus();

                            },
                          ),

                        ],
                      )
                  ),
                )
              ],
            ),
          )
        ));
  }

  List<Widget>commentWidget(){

    List<Widget> page = [];
    for(int i = 0;i<commentList.length;i++){

      // int likeStr = int.parse(widget.commentList[i]['fabulous_number']);
      //
      // Uint8List bytes = base64.decode(widget.commentList[i]['image_small']);

      NewsDetailCommentItemModel model = commentList[i];

      page.add(
          ListTile(
            title: Container(

              child: Row(
                mainAxisAlignment:MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      // Container(
                      //   clipBehavior: Clip.antiAlias,
                      //   margin: EdgeInsets.only(right: 10),
                      //   child: Image.memory(bytes,fit: BoxFit.cover,),
                      //   width: 25,
                      //   height: 25,
                      //   decoration: BoxDecoration(
                      //     borderRadius: BorderRadius.all(Radius.circular(25/2)),
                      //   ),
                      // ),
                      Text(
                        '${model.author}',style: TextStyle(fontSize: 12,fontWeight: FontWeight.w700),
                      ),
                    ],
                  ),
                  TextButton(
                      onPressed: (){
                        showDialog(
                            barrierDismissible: true,//是否点击空白区域关闭对话框,默认为true，可以关闭
                            context: context,
                            builder: (BuildContext context) {
                              var list = [];
                              list.add('色情低俗');
                              list.add('政治敏感');
                              list.add('广告');
                              list.add('令人恶心');
                              list.add('其他');
                              return BottomSheetWidget(
                                list: list,
                                onItemClickListener: (index) async {
                                  // LKToast.toast(context,msg: '举报成功，我们将随后处理您的举报');
                                  BotToast.showText(text: '举报成功，我们将随后处理您的举报');
                                  print( list[index]);
                                  Navigator.pop(context);
                                },
                              );
                            });
                      }, child: Text('举报',style: TextStyle(fontSize: 12),)),
                ],
              ),
            ),
            subtitle: Container(
              color: Colors.transparent,
              padding: EdgeInsets.only(top: 5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(model.comment,style: TextStyle(fontSize: 15,color: Colors.black87),),
                  SizedBox(height: 20,),
                  Row(
                    children: [
                      Container(
                        // color: Colors.red,
                        child: Text(model.dateBeauty,style: TextStyle(fontSize: 10,color: Colors.grey),),
                      ),
                      // GestureDetector(
                      //   onTap: (){
                      //     // comment
                      //
                      //     FocusScope.of(context).requestFocus(_commentFocus); // 获取焦点
                      //
                      //     hintTextStr = '回复${model.author}:';
                      //     replyId = model.id;
                      //
                      //     print('${i}');
                      //   },
                      //   child:Container(
                      //     alignment: Alignment.centerLeft,
                      //     margin: EdgeInsets.only(left: 15),
                      //     // color: Colors.yellow,
                      //     child: Text('回复',style: TextStyle(fontSize: 11,color: AppColor.smallTextColor),),
                      //   ),
                      // ),
                    ],
                  ),
                  model.children!.isEmpty?Container():Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(6.0),
                        ),
                        color: AppColor.bgColor,
                      ),
                      margin: EdgeInsets.only(top: 15),
                      padding: EdgeInsets.all(5),

                      constraints: BoxConstraints(
                          maxHeight: 100,
                          minHeight: 0
                      ),
                      child:GestureDetector(
                        onTap: (){
                          print('111');
                          Get.bottomSheet(NewsCommenDetailPage(model),
                              isScrollControlled: true);
                        },
                        child: ListView.builder(
                          padding: EdgeInsets.all(0),
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              margin: EdgeInsets.only(top: 5,bottom: 5),
                              // color: Colors.white,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Text('${model.children![index]['author']}:',style: TextStyle(
                                          fontSize: 12,color: AppColor.textColor,fontWeight: FontWeight.w500
                                      ),),
                                      Container(
                                        // color: Colors.red,
                                        width: Get.width-150,
                                        child: Text('${model.children![index]['comment']}',style: TextStyle(
                                          fontSize: 12,overflow: TextOverflow.ellipsis,
                                        ),maxLines: 1,),
                                      )
                                    ],
                                  ),

                                ],
                              ),
                            );
                          },itemCount:model.children!.isEmpty?0:model.children!.length>=  3?3:model.children!.length,),
                      ),
                  )
                ],
              ),
            ),

          )
      );
    }
    return page;
  }
}




